//
//  ConnectionHandler.m
//  TwitterClient3
//
//  Created by goccy on 11/10/29.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ConnectionHandler.h"

@implementation ConnectionHandler

- (id)init {
	self = [super init];
	if (self) {
		receivedData = [[NSMutableData alloc] init];
	}
	return self;
}

-(void)setTimelineController:(TimeLine *)timeline
{
	timelineController = timeline;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	NSString *encodingName = [response textEncodingName];
	NSLog(@"code: %@", encodingName);
	if ([encodingName isEqualToString: @"euc-jp"]) {
		receivedDataEncoding = NSJapaneseEUCStringEncoding;
	} else if ([encodingName isEqualToString:@"shift-jis"]) {
		receivedDataEncoding = NSShiftJISStringEncoding;
	} else {
		receivedDataEncoding = NSUTF8StringEncoding;
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	//NSString *resultString = [[NSString alloc] initWithData:data encoding:NSShiftJISStringEncoding];
	NSString *resultString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	if (resultString) {
		[receivedData appendData:data];
	}
	//NSString *resultString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];	
}

// データの取得が終了したときに呼び出される
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	NSString *result = [[NSString alloc] initWithData:receivedData encoding:receivedDataEncoding];
	//NSLog(@"receive complete: %@", result);
	NSString *resultString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
	//NSString *resultString = [[NSString alloc] initWithData:receivedData encoding:NSShiftJISStringEncoding];	
	//NSLog(@"%@", resultString);
	[timelineController displayTimeline:resultString];
	[result release];
	[receivedData release];
}

@end
